package websocket

import (
	"encoding/json"
	"fmt"
	"log"
	"time"

	"github.com/gorilla/websocket"
	"loomi2.0/core"
	"loomi2.0/models"
)

const (
	// 写入等待时间
	writeWait = 10 * time.Second
	
	// Pong等待时间
	pongWait = 60 * time.Second
	
	// Ping周期，必须小于pongWait
	pingPeriod = (pongWait * 9) / 10
	
	// 最大消息大小
	maxMessageSize = 512
)

// readPump 处理从客户端读取消息
func (c *Client) readPump() {
	defer func() {
		c.server.unregister <- c
		c.conn.Close()
	}()
	
	c.conn.SetReadLimit(maxMessageSize)
	c.conn.SetReadDeadline(time.Now().Add(pongWait))
	c.conn.SetPongHandler(func(string) error {
		c.conn.SetReadDeadline(time.Now().Add(pongWait))
		return nil
	})
	
	for {
		_, messageBytes, err := c.conn.ReadMessage()
		if err != nil {
			if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
				log.Printf("WebSocket错误: %v", err)
			}
			break
		}
		
		// 更新最后活跃时间
		c.lastSeen = time.Now()
		
		// 处理消息
		c.handleMessage(messageBytes)
	}
}

// writePump 处理向客户端写入消息
func (c *Client) writePump() {
	ticker := time.NewTicker(pingPeriod)
	defer func() {
		ticker.Stop()
		c.conn.Close()
	}()
	
	for {
		select {
		case message, ok := <-c.send:
			c.conn.SetWriteDeadline(time.Now().Add(writeWait))
			if !ok {
				c.conn.WriteMessage(websocket.CloseMessage, []byte{})
				return
			}
			
			w, err := c.conn.NextWriter(websocket.TextMessage)
			if err != nil {
				return
			}
			w.Write(message)
			
			// 添加队列中的其他消息
			n := len(c.send)
			for i := 0; i < n; i++ {
				w.Write([]byte{'\n'})
				w.Write(<-c.send)
			}
			
			if err := w.Close(); err != nil {
				return
			}
			
		case <-ticker.C:
			c.conn.SetWriteDeadline(time.Now().Add(writeWait))
			if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
				return
			}
		}
	}
}

// handleMessage 处理接收到的消息
func (c *Client) handleMessage(messageBytes []byte) {
	var msg Message
	if err := json.Unmarshal(messageBytes, &msg); err != nil {
		log.Printf("消息解析失败: %v", err)
		c.sendError("消息格式错误")
		return
	}
	
	// 设置客户端ID
	msg.ClientID = c.id
	msg.Timestamp = time.Now()
	
	log.Printf("收到消息 [%s]: %s", msg.Type, msg.Content)
	
	// 根据消息类型处理
	switch msg.Type {
	case "chat":
		c.handleChatMessage(msg)
	case "task":
		c.handleTaskMessage(msg)
	case "status":
		c.handleStatusMessage(msg)
	case "ping":
		c.handlePingMessage(msg)
	default:
		c.sendError(fmt.Sprintf("未知消息类型: %s", msg.Type))
	}
}

// handleChatMessage 处理聊天消息
func (c *Client) handleChatMessage(msg Message) {
	// 获取对话管理器
	conversationManager := core.GetConversationManager()
	if conversationManager == nil {
		c.sendError("对话管理器未初始化")
		return
	}
	
	// 添加用户消息
	conversationManager.AddMessage("user", msg.Content)
	
	// 发送确认响应
	c.sendResponse(Response{
		Type:      "chat_received",
		Success:   true,
		Message:   "消息已接收",
		Data:      map[string]string{"message_id": fmt.Sprintf("%d", time.Now().UnixNano())},
		Timestamp: time.Now(),
	})
	
	// 异步处理AI响应
	go c.processAIResponse(msg.Content)
}

// processAIResponse 处理AI响应
func (c *Client) processAIResponse(userInput string) {
	// 获取模型管理器
	modelManager := models.GetModelManager()
	if modelManager == nil {
		c.sendError("模型管理器未初始化")
		return
	}
	
	// 发送处理中状态
	c.sendResponse(Response{
		Type:      "ai_processing",
		Success:   true,
		Message:   "AI正在处理中...",
		Timestamp: time.Now(),
	})
	
	// 这里可以集成现有的AI处理逻辑
	// 暂时返回一个模拟响应
	time.Sleep(1 * time.Second) // 模拟处理时间
	
	aiResponse := fmt.Sprintf("AI回复: 我收到了您的消息「%s」，这是一个模拟回复。", userInput)
	
	// 添加AI消息到对话历史
	conversationManager := core.GetConversationManager()
	if conversationManager != nil {
		conversationManager.AddMessage("assistant", aiResponse)
	}
	
	// 发送AI响应
	c.sendResponse(Response{
		Type:      "ai_response",
		Success:   true,
		Message:   "AI响应完成",
		Data: map[string]interface{}{
			"response": aiResponse,
			"model":    "current_model", // 可以从模型管理器获取当前模型
		},
		Timestamp: time.Now(),
	})
}

// handleTaskMessage 处理任务消息
func (c *Client) handleTaskMessage(msg Message) {
	workspace := core.GetWorkspace()
	if workspace == nil {
		c.sendError("工作空间未初始化")
		return
	}
	
	// 添加任务到工作空间
	workspace.AddTask(msg.Content)
	
	c.sendResponse(Response{
		Type:      "task_added",
		Success:   true,
		Message:   "任务已添加",
		Data: map[string]interface{}{
			"task":  msg.Content,
			"tasks": workspace.GetTasks(),
		},
		Timestamp: time.Now(),
	})
}

// handleStatusMessage 处理状态查询消息
func (c *Client) handleStatusMessage(msg Message) {
	workspace := core.GetWorkspace()
	conversationManager := core.GetConversationManager()
	modelManager := models.GetModelManager()
	
	status := map[string]interface{}{
		"server_time": time.Now(),
		"client_id":   c.id,
		"uptime":      time.Since(c.lastSeen),
	}
	
	if workspace != nil {
		status["workspace"] = map[string]interface{}{
			"notes_count": len(workspace.GetNotes()),
			"tasks_count": len(workspace.GetTasks()),
		}
	}
	
	if conversationManager != nil {
		status["conversation"] = map[string]interface{}{
			"messages_count": len(conversationManager.GetMessages()),
		}
	}
	
	if modelManager != nil {
		status["models"] = map[string]interface{}{
			"available_models": models.GetAvailableModels(),
			"session_stats":    models.GetSessionStats(),
		}
	}
	
	c.sendResponse(Response{
		Type:      "status",
		Success:   true,
		Message:   "系统状态",
		Data:      status,
		Timestamp: time.Now(),
	})
}

// handlePingMessage 处理ping消息
func (c *Client) handlePingMessage(msg Message) {
	c.sendResponse(Response{
		Type:      "pong",
		Success:   true,
		Message:   "pong",
		Data:      map[string]string{"client_id": c.id},
		Timestamp: time.Now(),
	})
}

// sendResponse 发送响应消息
func (c *Client) sendResponse(response Response) {
	data, err := json.Marshal(response)
	if err != nil {
		log.Printf("响应序列化失败: %v", err)
		return
	}
	
	select {
	case c.send <- data:
	default:
		log.Println("客户端发送通道已满")
	}
}

// sendError 发送错误消息
func (c *Client) sendError(message string) {
	c.sendResponse(Response{
		Type:      "error",
		Success:   false,
		Message:   message,
		Timestamp: time.Now(),
	})
}